09. Update state with setState
Update State With SetState
Using SetState To Remove Contact
How State is Set
Earlier in this lesson, we saw how we can define a component's state at the time of initialization. Since state reflects mutable information that ultimately affects rendered output, a component may also update its state throughout its lifecycle using this.setState()
. As we've learned, when local state changes, React will trigger a re-render of the component.
There are two ways to use setState()
. The first is to merge state updates. Consider a snippet of the following component:
class Email extends React.Component {
state = {
subject: '',
message: ''
}
// ...
});
Though the initial state of this component contains two properties (subject
and message
), they can be updated independently. For example:
this.setState({
subject: 'Hello! This is a new subject'
})
This way, we can leave this.state.message
as-is, but replace this.state.subject
with a new value.
The second way we can use setState()
is by passing in a function rather than an object. For example:
this.setState((prevState) => ({
count: prevState.count + 1
}))
Here, the function passed in takes a single prevState
argument. When a component's new state depends on the previous state (i.e., we are incrementing count
in the previous state by 1), we want to use the functional setState()
.
Facts About Updating State?
SOLUTION:
- Whenever `setState()` is called, the component also calls `render()` with the new state
- State updates can be merged by passing in an object to `setState()`
- State updates can be asynchronous (i.e., `setState()` can accept a function with the previous state as its first argument)
setState()
Recap
While a component can set its state when it initializes, we expect that state to change over time, usually due to user input. The component is able to change its own internal state using this.setState()
. Each time state is changed, React knows and will call render()
to re-render the component. This allows for fast, efficient updates to your app's UI.
Further Research
- Using State Correctly from the React Docs